package face.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

import org.bytedeco.javacpp.opencv_core.Mat;

/**
 * 数据类型转换
 * @author ShiQiang
 *
 */
public class ConverterData{
	/**
	 * 将mat转BufferedImage
	 * @param matrix 
	 */
	public static BufferedImage m2B(Mat matrix) { 
		int cols=matrix.cols();
		int rows=matrix.rows();
		int elemSize=(int)matrix.elemSize();
		byte[] data=new byte[cols*rows*elemSize];
		
		matrix.data().get(data); 
		
		int type = 0; 
		switch(matrix.channels()){
		case 1:
			type=BufferedImage.TYPE_BYTE_GRAY;
			break;
		case 3:
			type=BufferedImage.TYPE_3BYTE_BGR;
			byte b;
			for(int i=0;i<data.length;i=i+3){
				b=data[i];
				data[i]=data[i+2];
				data[i+2]=b;
			}
			break;
		default:
			return null; 
		}
		BufferedImage image=new BufferedImage(cols,rows,type);
		image.getRaster().setDataElements(0, 0,cols,rows,data);
		return image;
	} 

    /**
     * 将bufferImage转Mat
     * @param original	
     * @param imgType
     * @param matType
     * @param msg
     * @param x
     * @param y 
     */
    public static Mat b2M(BufferedImage original,int matType,String msg,int x,int y) {
        Graphics2D g = original.createGraphics();
        try {
            g.setComposite(AlphaComposite.Src);
            g.drawImage(original, 0, 0, null);
            g.drawString(msg, x, y);
        } finally {
            g.dispose();
        } 
        Mat mat = new Mat(original.getHeight(), original.getWidth(), matType); 
        mat.data().put(((DataBufferByte) original.getRaster().getDataBuffer()).getData()); 
        return mat;
    } 
}
